package com.android.happymall.activity.mine;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.happymall.R;
import com.android.happymall.activity.BaseObject;
import com.android.happymall.app.BaseActivity;
import com.android.happymall.fragment.detail.Fragment_AuctioningRule;
import com.android.happymall.fragment.group.Fragment_Orderts_History;
import com.android.happymall.fragment.group.Fragment_PastedTurnover;
import com.android.happymall.model.auction.Auction_DetailRecentlyData;
import com.android.happymall.model.auction.Auction_OrderDetailData;
import com.android.happymall.model.auction.Auction_OrderDetailDataCallback;
import com.android.happymall.model.auction.Auction_detail_rule;
import com.android.happymall.model.auction.Auction_detail_ruleCallback;
import com.android.happymall.model.auction.Auction_pastedturnover;
import com.android.happymall.model.detail.Banner;
import com.android.happymall.model.group.MainList;
import com.android.happymall.utils.ConstantsUrl;
import com.android.happymall.utils.HttpUtils;
import com.android.happymall.utils.LoginState;
import com.android.happymall.utils.MyLog;
import com.android.happymall.utils.ObjectUtils;
import com.android.happymall.view.CustomViewpager;
import com.android.happymall.view.RY_Scrollview;
import com.android.happymall.view.group.ViewPagerIndicator;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/11/6.
 */

public class GoodsDetailActivity1 extends BaseActivity {
    @BindView(R.id.bannerpager_fragment)
    ViewPager bannerpager_fragment;
    @BindView(R.id.viewPagerIndicator1)
    ViewPagerIndicator viewPagerIndicator1;
    @BindView(R.id.viewpager)
    CustomViewpager viewpager;
    @BindView(R.id.refreshLayout)
    TwinklingRefreshLayout refreshLayout;
    @BindView(R.id.scollview)
    RY_Scrollview scrollview;
    @BindView(R.id.bid_auction)
    TextView bidauction;
    @BindView(R.id.rightnow_price)
    TextView rightnow_price;
    @BindView(R.id.market_price)
    TextView market_price;
    @BindView(R.id.product_name)
    TextView product_name;
    @BindView(R.id.begin_price)
    TextView begin_price;
    @BindView(R.id.addprice_range)
    TextView addprice_range;
    @BindView(R.id.brokerage)
    TextView brokerage;
    @BindView(R.id.auctioning_counttime)
    TextView auctioning_counttime;
    @BindView(R.id.reutrns_rate)
    TextView reutrns_rate;
    @BindView(R.id.kill_minute)
    TextView kill_minute;
    @BindView(R.id.kill_second)
    TextView kill_second;
    @BindView(R.id.kill_millsecond)
    TextView kill_millsecond;
    @BindView(R.id.no_bidhistory)
    TextView no_bidhistory;
    @BindView(R.id.bid_history)
    LinearLayout bid_history;
    @BindView(R.id.detail_grid_sort)
    NestFullListView detail_grid_sort;
    @BindView(R.id.have_consumered_money)
    TextView have_consumered_money;
    @BindView(R.id.detail_goods_ll)
    LinearLayout detail_goods_ll;
    @BindView(R.id.shareing_order_lt)
    RelativeLayout shareing_order_lt;
    @BindView(R.id.past_turnover_lt)
    RelativeLayout past_turnover_lt;
    @BindView(R.id.auction_rule_lt)
    RelativeLayout auction_rule_lt;
    @BindView(R.id.shareing_order_v)
    View shareing_order_v;
    @BindView(R.id.past_turnover_v)
    View past_turnover_v;
    @BindView(R.id.auction_rule_v)
    View auction_rule_v;
    private FragmentActivity mcontext;
    private GroupFragmentPagerAdapters pagerAdapter;
    private ArrayList<String> Banner = new ArrayList<>();
    private boolean networkConnected;

    private ArrayList<com.android.happymall.model.detail.Banner.Bannerdata> Bannerlist = new ArrayList<>();
    private ArrayList<MainList.MainListdata.Mainlistdata> listdata ;
    private ArrayList<Auction_DetailRecentlyData.ListBean> bh_listdata  = new ArrayList<>();;
    private int mid;
    private String token;
    private String id;
    private Message message;
    private Handler mHandler,mHandler1,mHandler2;
    private boolean isshareing_order=true;
    private boolean ispast_turnover;
    private boolean isauction_rule;
    private String rule;
    AlertDialog dialog;
    private int count = 0;
    private float summary_price = 0;
    private int time;
    private int start;
    private   String auction_id;
    private String order_sn;
    private int DETAIL_SHOW;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_detail_goods);
        mcontext = GoodsDetailActivity1.this;
        ButterKnife.bind(this);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        DETAIL_SHOW = getIntent().getIntExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW,0);
        if(!LoginState.getInstance().getid(mcontext).equals("")&&LoginState.getInstance().getid(mcontext)!=null) {
            mid = Integer.parseInt(LoginState.getInstance().getid(mcontext));
            token = LoginState.getInstance().getUserInfo(mcontext,2);
        }
        init();
        initData();
    }
    public void setHandler(Handler handler) {
        mHandler = handler;
    }
    public void setHandler1(Handler handler) {
        mHandler1 = handler;
    }
    public void setHandler2(Handler handler) {
        mHandler2 = handler;
    }
    public  void notifyFinish()
    {
        refreshLayout.finishLoadmore();
    }

    private void init() {
//        history_trending_chart.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent trend_chart = new Intent(mcontext,BaseObject.class);
//                trend_chart.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE,"历史成交走势图");
//                startActivity(trend_chart);
//            }
//        });
        bidauction.setText("立即参与");
        bidauction.setBackgroundResource(R.drawable.corner_red_bg_selector);
        detail_grid_sort.setAdapter(new NestFullListViewAdapter<Auction_DetailRecentlyData.ListBean>(R.layout.item_detail_bh_grid,bh_listdata ) {
            @Override
            public void onBind(int position, Auction_DetailRecentlyData.ListBean testBean, NestFullViewHolder holder) {
                if(testBean.getUsername().equals("")||testBean.getUsername()==null)
                {
                    holder.setVisible(R.id.item_grid_detail_like_ll,true);
                    holder.setVisible(R.id.item_grid_detail_like_ll1,false);
                }
                else
                {
                    holder.setVisible(R.id.item_grid_detail_like_ll,false);
                    holder.setVisible(R.id.item_grid_detail_like_ll1,true);
                    holder.setText(R.id.getting_tv, testBean.getGetting());
                    ObjectUtils.photoCircle(mcontext,testBean.getPhoto(),(ImageView)holder.getView(R.id.item_detail_bidhistoryimg1));
                    if(position==0)
                    {
                        holder.setBackgroundRes(R.id.getting_ll,R.drawable.corner_red_bg2);
                    }
                    else
                    {
                        holder.setBackgroundRes(R.id.getting_ll,R.drawable.corner_gray_bg2);
                    }
                    holder.setText(R.id.username, testBean.getUsername());
                    holder.setText(R.id.city, testBean.getCity());
                    int time = Integer.parseInt(testBean.getC_time());
                    long msl=(long)time*1000;
                    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                    String text = format.format(msl);
                    holder.setText(R.id.time,text);
                    holder.setText(R.id.money, "¥"+testBean.getPrice());
                }

            }
        });

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                viewpager.resetHeight(position);
                switch (position)
                {
                    case 0:
                        isshareing_order = true;
                        ispast_turnover = false;
                        isauction_rule = false;
                        shareing_order_v.setVisibility(View.VISIBLE);
                        past_turnover_v.setVisibility(View.INVISIBLE);
                        auction_rule_v.setVisibility(View.INVISIBLE);
                        break;
                    case 1:
                        isshareing_order = false;
                        ispast_turnover = true;
                        isauction_rule = false;
                        shareing_order_v.setVisibility(View.INVISIBLE);
                        past_turnover_v.setVisibility(View.VISIBLE);
                        auction_rule_v.setVisibility(View.INVISIBLE);
                        break;
                    case 2:
                        isshareing_order = false;
                        ispast_turnover = false;
                        isauction_rule = true;
                        shareing_order_v.setVisibility(View.INVISIBLE);
                        past_turnover_v.setVisibility(View.INVISIBLE);
                        auction_rule_v.setVisibility(View.VISIBLE);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewpager.resetHeight(0);
        scrollview.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter(){
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.finishRefreshing();
                    }
                },1000);
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                if(isshareing_order) {
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                }
                else if(ispast_turnover)
                {
                    Message msg = new Message();
                    msg.what = 2;
                    mHandler1.sendMessage(msg);
                }
                else
                {
                    Message msg = new Message();
                    msg.what = 3;
                    mHandler2.sendMessage(msg);
                }
            }
        });
    }
    private void  initData() {
        id = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID);
//        auctionDetailSendData.setType("get_auction");
//        auctionDetailSendData.setId(Integer.parseInt(id));
//        gsonstring = gson.toJson(auctionDetailSendData);
//        service.sendMsg(gsonstring);
        GetOrder_Detail();
        shareing_order_lt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isshareing_order = true;
                ispast_turnover = false;
                isauction_rule = false;
                shareing_order_v.setVisibility(View.VISIBLE);
                past_turnover_v.setVisibility(View.INVISIBLE);
                auction_rule_v.setVisibility(View.INVISIBLE);
                viewpager.setCurrentItem(0);
            }
        });
        past_turnover_lt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isshareing_order = false;
                ispast_turnover = true;
                isauction_rule = false;
                shareing_order_v.setVisibility(View.INVISIBLE);
                past_turnover_v.setVisibility(View.VISIBLE);
                auction_rule_v.setVisibility(View.INVISIBLE);
                viewpager.setCurrentItem(1);
            }
        });
        auction_rule_lt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isshareing_order = false;
                ispast_turnover = false;
                isauction_rule = true;
                shareing_order_v.setVisibility(View.INVISIBLE);
                past_turnover_v.setVisibility(View.INVISIBLE);
                auction_rule_v.setVisibility(View.VISIBLE);
                viewpager.setCurrentItem(2);
            }
        });
    }

    @OnClick({R.id.contact_aishang,R.id.bid_history,R.id.detail_goods_ll,R.id.history_trending_ll,R.id.bid_auction,R.id.main_top_back})
    public void onClick(View v) {
        switch (v.getId()) {
            case  R.id.contact_aishang:
                getAgreeMentData();
                break;
            case R.id.bid_history:
                Intent intent_address1 = new Intent(mcontext, BaseObject.class);
                intent_address1.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "出价记录");
                intent_address1.putExtra("order_sn",order_sn);
                startActivity(intent_address1);
                break;
            case R.id.detail_goods_ll:
                Intent intent_address2 = new Intent(mcontext, BaseObject.class);
                intent_address2.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "商品详情");
                intent_address2.putExtra("detail_goodsid",id);
                startActivity(intent_address2);
                break;
            case R.id.history_trending_ll:
                Intent intent_q = new Intent(mcontext, NewGuideActivity.class);
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL,"https://jm.lnest.cc/home/www/?/#/auction-charts/"+id);
                intent_q.putExtra("title","历史成交走势图");
                startActivity(intent_q);
//                Intent intent_address3 = new Intent(mcontext, BaseObject.class);
//                intent_address3.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "历史成交走势图");
//                intent_address3.putExtra("detail_htc","https://jm.lnest.cc/home/www/?/#/auction-charts/"+id);
//                startActivity(intent_address3);
                break;
            case R.id.main_top_back:
//                Intent intent = new Intent();
//                Bundle bundle = new Bundle();
//                bundle.putString("auction_id",auction_detail.getAuction().getId());
//                bundle.putString("auction_period",auction_detail.getAuction().getPeriod());
//                intent.putExtras(bundle);
//                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.bid_auction:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ObjectUtils.ToDetailActivity(mcontext, 1, id, "");
                    finish();
                }
                else
                {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
        }
    }
    //获取详情
    private void GetOrder_Detail() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.ACUTIONORDER_DETAIL;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            map.put("order_id",id);
            HttpUtils.get(address, header, map,order_detailCallback);
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    Auction_OrderDetailDataCallback order_detailCallback= new Auction_OrderDetailDataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
        }

        @Override
        public void onResponse(Auction_OrderDetailData response, int id) {
            if(response.getCode()==0) {
                rightnow_price.setText("￥" +response.getData().getPrice());
                String markprice = response.getData().getMarket_price();
                market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                market_price.setText("￥" + markprice);
                product_name.setText(response.getData().getTitle());
                begin_price.setText("￥" + response.getData().getStart_price());
                addprice_range.setText("￥" +response.getData().getPer_price());
                brokerage.setText(response.getData().getBrokerage()+"趣豆");
                auctioning_counttime.setText(response.getData().getFirst_countdown()+"秒");
                reutrns_rate.setText(response.getData().getReturns_rate()+" (1个趣豆退"+response.getData().getReturns_rate()+"个积分)");
                order_sn = response.getData().getOrder_sn();
                auction_id = response.getData().getAuction_id();

                GetBanner(response.getData().getThumbs());
                pagerAdapter = new GroupFragmentPagerAdapters(getSupportFragmentManager());
                viewpager.setAdapter(pagerAdapter);
                viewpager.setCurrentItem(0);
                if(response.getData().getMid()!=null) {
                    bh_listdata.clear();
//                    bh_listdata.add(new Auction_DetailRecentlyData.ListBean(Auction_pastedturnover.ListBean.THREE, "抢先"
//                            , response.getData().getMid(), response.getData().getUsername(),response.getData().getPhoto()
//                            , recentlyData.getList().get(i).getType(), recentlyData.getList().get(i).getIp(), recentlyData.getList().get(i).getCity(),response.getData().getC_time()
//                            ,response.getData().getPrice()));
                    bh_listdata.add(new Auction_DetailRecentlyData.ListBean(Auction_pastedturnover.ListBean.THREE, "没抢到"
                            , "", "", "", "", "", "", "", ""));
                    bh_listdata.add(new Auction_DetailRecentlyData.ListBean(Auction_pastedturnover.ListBean.THREE, "没抢到"
                            , "", "", "", "", "", "", "", ""));

                    detail_grid_sort.updateUI();
                    no_bidhistory.setVisibility(View.INVISIBLE);
                    detail_grid_sort.setVisibility(View.VISIBLE);
                }
                else
                {
                    no_bidhistory.setVisibility(View.VISIBLE);
                    detail_grid_sort.setVisibility(View.INVISIBLE);
                }
            }
        }
    };

    //获取趣买规则
    private void getAgreeMentData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.ACUTIONHOMEBLOCK;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            map.put("mark","agreement");
            HttpUtils.get(address, header, map, dataCallback);
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    Auction_detail_ruleCallback dataCallback= new Auction_detail_ruleCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
        }

        @Override
        public void onResponse(Auction_detail_rule response, int id) {
            if(response.getCode()==0) {
                rule = response.getData();
                showRuleDialog();
            }
        }
    };
    private void showRuleDialog() {
        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.detail_signin_rule, null);
        TextView sure = (TextView) v.findViewById(R.id.dialog_sure);
        TextView content = (TextView) v.findViewById(R.id.dialog_content);
        content.setText(Html.fromHtml(rule));
        sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        dialog.dismiss();
                                    }
                                }
        );
        dialog = new AlertDialog.Builder(mcontext).setView(v).setCancelable(true).show();
    }
//    /**
//     * 处理竞买返回通知消息
//     */
//    private void DealWithResult()
//    {
//        /**
//         * 趣买返回通知重开
//         */
//        if(auctionResultData.getTime()>0)
//        {
//            /**
//             * 更新重开的商品时间
//             */
//            if (auction_detail != null) {
//                if (auctionResultData.getId().equals(id)) {
//                    bidauction.setText("进入最新一期");
//                    bidauction.setEnabled(true);
//                    bidauction.setBackgroundResource(R.drawable.corner_red_bg_selector);
////                    currenttime = auctionResultData.getTime() * 1000;
////                    currentstart =auctionResultData.getStart() * 1000;
////                    auction_detail.getAuction().setTime(auctionResultData.getTime() * 1000);
////                    if(auctionResultData.getStart()>0)
////                    {
////                        isstart = true;
////                    auction_detail.getAuction().setStart(auctionResultData.getStart() * 1000);
////                        }
//                }
//            }
//        }
//
//    }
    private class GroupFragmentPagerAdapters extends FragmentPagerAdapter {
        public GroupFragmentPagerAdapters(FragmentManager fm) {
            super(fm);
        }


        @Override
        public Fragment getItem(int position) {
            if(position==2)

            {
                Fragment_AuctioningRule fragment_AuctioningRule = new Fragment_AuctioningRule();
                fragment_AuctioningRule.SecurityInfoFragment(viewpager, position,auction_id);
                return  fragment_AuctioningRule;

            }
            else if(position==0)
            {
                Fragment_Orderts_History Orderts_History= new Fragment_Orderts_History();
                Orderts_History.SecurityInfoFragment(viewpager, position,auction_id);
                return Orderts_History;

            }
            else
            {
                Fragment_PastedTurnover fragment_bidHistory = new Fragment_PastedTurnover();
                fragment_bidHistory.SecurityInfoFragment(viewpager, position,auction_id);
                return fragment_bidHistory;
            }
        }

        @Override
        public int getCount() {
            return 3;

        }

    }
    /**
     * 获取轮播图
     */
    private void GetBanner(String[] thumbs)
    {
        Bannerlist.clear();

            for (int i = 0; i < thumbs.length; i++) {
                com.android.happymall.model.detail.Banner.Bannerdata data = new Banner.Bannerdata();
                data.setThumb(thumbs[i]);
                data.setLink("");
                data.setPath("");
                Bannerlist.add(data);
            }
            //轮播图
            if(Bannerlist!=null) {
                viewPagerIndicator1.autoScroll(mcontext.getSupportFragmentManager(),bannerpager_fragment, 1);
                viewPagerIndicator1.setViewPager(Bannerlist);
                viewPagerIndicator1.setNotifyDataSetChanged();
            }

    }

    /**
     * 轮播图销毁开启
     */

    @Override
    public void onStart() {
        super.onStart();

        viewPagerIndicator1.setVisible(true);
    }


    @Override
    public void onPause() {
        super.onPause();

        viewPagerIndicator1.setVisible(false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

//            Intent intent = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putString("auction_id",auction_detail.getAuction().getId());
//            bundle.putString("auction_period",auction_detail.getAuction().getPeriod());
//            intent.putExtras(bundle);
//            setResult(RESULT_OK, intent);
//            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

